<template>
  <div class="interface-container">
    <el-row :gutter="10" class="main-content">
      <!-- 左边内容 -->
      <el-col :xs="24" :sm="8" :md="6" :lg="6" :xl="5" class="left-panel">
        <treeNode @treeClick="handleTreeClick" :handleTreeClick="handleTreeClick"></treeNode>
      </el-col>
      <!-- 右边内容 -->
      <el-col :xs="24" :sm="16" :md="18" :lg="18" :xl="19" class="right-content">
        <div class="search-area">
          <el-input style="width: 100%; max-width: 300px; margin-right: 10px; margin-bottom: 10px;" v-model="filterText.name" placeholder="请输入接口名称" clearable>
          </el-input>
          <el-select v-model="filterText.status" placeholder="选择查询状态" style="width: 100%; max-width: 150px; margin-right: 10px; margin-bottom: 10px;" clearable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" @click="handlenewInterfacesClick" style="margin-bottom: 10px;">查询</el-button>
          <el-button @click="filterText={status: '',name:''}" style="margin-bottom: 10px;">重置</el-button>
        </div>
        <div class="action-buttons">
          <div class="button-group">
            <el-button
              type="danger"
              @click="delAllInterface"
              style="margin-right: 10px; margin-bottom: 10px;"
                >
              <el-icon style="margin-right: 6px"><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button
              type="primary"
              @click="clickAdd"
              style="margin-right: 10px; margin-bottom: 10px;"
                >
              <el-icon style="margin-right: 6px"><Plus /></el-icon>
              新增接口
            </el-button>
            <el-button
              :type="showOnlySelf ? 'success' : 'primary'"
              @click="userInterface"
              style="margin-right: 10px; margin-bottom: 10px;"
                >
              <el-icon style="margin-right: 6px"><View /></el-icon>
              {{buttonText}}
            </el-button>
            <el-button
              type="primary"
              @click="dialogVisible = true"
              style="margin-right: 10px; margin-bottom: 10px;"
                >
              <el-icon style="margin-right: 6px"><Star /></el-icon>
              选择环境
            </el-button>
          </div>
          <div class="env-info">
            <span style="font-size: 14px; color: #909399; margin-right: 10px; margin-bottom: 10px; display: inline-block;">当前环境：
                <el-button
                  type="info"
                  disabled
                  plain
                  >{{ currentEnv ? currentEnv.name : '未知环境' }}</el-button>
            </span>
            <el-button
              type="warning"
              @click="importClick"
              style="margin-bottom: 10px;"
                >
              <el-icon><Upload /></el-icon>
              导入接口
            </el-button>
          </div>
        </div>
        <el-dialog v-model="dialogVisible" width="30%" title="选择环境">
          <el-form :rules="rulesinterface" ref="interfaceRef" >
            <el-form-item label="测试环境" prop="env">
              <el-select v-model.lazy="selectedEnvironment" placeholder="请选择环境" style="width: 70%;" no-data-text="暂无数据">
                <el-option v-for="item in testEnvs" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmSelection">确定</el-button>
          </span>
          </template>
        </el-dialog>
        <div class="interface-title">全部接口共 ({{interfaceCount}}) 个</div>
        <el-scrollbar class="interface-scrollbar">
          <div class="interface-list">
            <div 
              v-for="item in tableData" 
              :key="item.id" 
              class="interface-item"
              :class="[
                {'interface-item-selected': multipleSelection.includes(item.id)},
                `method-${item.method.toLowerCase()}`
              ]"
            >
              <div class="interface-checkbox">
                <el-checkbox 
                  :value="multipleSelection.includes(item.id)" 
                  @change="(val) => handleSingleSelect(val, item.id)"
                ></el-checkbox>
              </div>
              <div class="interface-content" @click="clickCopy(item.id)">
                <div class="method-section">
                  <el-tag v-if="item.method === 'POST'" color="#49cc90">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'GET'" color="#61affe">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'PUT'" color="#fca130">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'PATCH'" color="#50e3c2">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'DELETE'" color="#f93e3e">{{ item.method }}</el-tag>
                  <el-tag v-if="item.method === 'DEAD'" color="rgb(201, 233, 104)">{{ item.method }}</el-tag>
                </div>
                <div class="info-section">
                  <div class="interface-url" :title="item.url">{{ item.url }}</div>
                  <div class="interface-name" :title="item.name">{{ item.name }}</div>
                </div>
                <div class="status-section" @click.stop>
                  <el-dropdown trigger="click" @command="val => statusClick(val, item.id)">
                    <span class="status-text" :style="{ color: buttonColor(item.status) }">
                      <el-icon v-if="item.status!='状态'" :style="{ color: buttonColor(item.status) }"><Flag /></el-icon>
                      {{ item.status }}
                      <el-icon><ArrowDown /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="已发布" style="color:#67C23A">
                          <el-icon><Flag /></el-icon>
                          已发布
                        </el-dropdown-item>
                        <el-dropdown-item command="测试中" style="color:#626aef">
                          <el-icon><Flag /></el-icon>
                          测试中
                        </el-dropdown-item>
                        <el-dropdown-item command="开发中" style="color:#E6A23C">
                          <el-icon><Flag /></el-icon>
                          开发中
                        </el-dropdown-item>
                        <el-dropdown-item command="已废弃" style="color:#909399">
                          <el-icon><Flag /></el-icon>
                          已废弃
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="action-section" @click.stop>
                  <el-button type="text" @click="handleChildData(item)">接口Mock</el-button>
                  <el-button type="text" @click="clickEditStep(item.id)">调试</el-button>
                  <el-button type="text" @click="clickCopy(item.id)">复制</el-button>
                  <el-button type="text" @click="clickDel(item.id)">删除</el-button>
                  <el-button type="text" @click="clickLog">操作记录</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </el-col>
    </el-row>
  </div>
  
  <!-- 添加测试步骤窗口 -->
	<el-drawer v-model="addCaseDlg"  :destroy-on-close="true" :with-header="false" size="50%" @close="handleClose" ><addCase  :treeId="treeId" style="padding: 0 10px;" @close-dialog="handleClose"></addCase></el-drawer>
	<!-- 调试测试步骤窗口 -->
  <el-drawer v-model="editCaseDlg" :destroy-on-close="true" :with-header="false" size="50%" @close="handleClose"><newEditCase ref="childRef"   :Interface_id="Interface_id" :copyDlg="copyDlg"  style="padding: 0 10px;"></newEditCase></el-drawer>
  <!--  接口操作记录窗口-->
  <el-drawer v-model="logDlg"   :with-header="false" size="50%">
    <el-card>
				<b>接口操作记录</b>
				<div style="margin-top: 10px;">
					<el-timeline>
						<el-timeline-item v-for="(activity, index) in bugLogs"
                              :key="index"
                              :timestamp="$tools.rDate(activity.create_time)"
                              placement="top"
                              color="#0bbd87">
							<el-card>
								<h4>{{ activity.handle }}</h4>
                <p v-if="activity.remark">变更记录：{{ activity.remark }}</p>
                <span style="color: #409eff;margin-right: 8px">{{ activity.update_user }}</span>
                <span>操作于 {{ $tools.rTime(activity.create_time) }}</span>
							</el-card>
						</el-timeline-item>
					</el-timeline>
				</div>
			</el-card>
  </el-drawer>
  <!--  导入接口窗口-->
  <interfaceImport  v-if="importDlg" :importDlg="importDlg" @close-modal="handleCloseModal"></interfaceImport>
  <!--  mock弹窗-->
  <el-drawer v-model="mockDlg"  :destroy-on-close="true" :with-header="false" size="60%"  @close="handleClose" ><mockInterface :interfaceData="interfaceData"  style="padding: 0 10px;"></mockInterface></el-drawer>

</template>

<script>
import treeNode from './treeNode.vue';
import {ElMessage, ElMessageBox} from "element-plus";
import newEditCase from '../../components/common/InterfaceNew/neweditCase.vue';
import addCase from '../../components/common/InterfaceNew/addCase.vue';
import interfaceImport from '../../views/Interface/interfaceImport.vue';
import mockInterface from '../../views/Interface/mockInterface';
import {mapMutations, mapState} from "vuex";
import { Delete, Plus, View, Star, Upload, Flag, ArrowDown } from '@element-plus/icons-vue';

export default {
components: {
    treeNode,
    newEditCase,
    addCase,
    interfaceImport,
    mockInterface,
    Delete,
    Plus,
    View,
    Star,
    Upload,
    Flag,
    ArrowDown
  },
computed: {
    buttonText() {
      return this.showOnlySelf ? '取消只看自己创建' : '只看自己创建';
    },
    ...mapState(['pro','testEnvs','envId']),
    username() {
			return window.sessionStorage.getItem('username');
		},
   currentEnv() {
      if (!this.envId || !this.testEnvs || this.testEnvs.length === 0) return null;
      return this.testEnvs.find(env => env.id === this.envId) || this.testEnvs[0];
    },
    env: {
			get() {
				return this.envId;
			},
			set(val) {
				this.selectEnv(val);
			}
		},
    },
data() {
    return {
      treeId: '',
      filterText:{
        name:'',
        status:''
      },
      tableData: [],
      editCaseDlg: false,
      addCaseDlg: false,
      logDlg:false,
      importDlg:false,
      Interface_id: '',
      copyDlg: false,
      showOnlySelf: false,
      selectedOption:'',
      dialogVisible: false,
      selectedEnvironment: '',
      multipleSelection: [],
      bugLogs: [
        {
          create_time: "2024-02-18T10:30:00",
          handle: "修复了一个bug",
          remark: "这是修复bug的备注",
          update_user: "张三"
        },
        {
          create_time: "2024-02-17T14:20:00",
          handle: "重新测试了bug",
          remark: "接口名称登录变更为tms登录接口",
          update_user: "李四"
        },
        {
          create_time: "2024-02-16T09:45:00",
          handle: "提交了一个新的bug",
          update_user: "王五"
        }
        ],
      interfaceCount: 0,
      options: [
          { value: '开发中', label: '开发中' },
          { value: '测试中', label: '测试中' },
          { value: '已发布', label: '已发布' },
          { value: '已废弃', label: '已废弃' },
      ],
      mockDlg: false,
    };
  },
  methods: {
  ...mapMutations(['selectEnv']),
    // 把批量选择完成的数据取出id重新生成数组
    handleSelectionChange(selected) {
      this.multipleSelection = selected.map(item => item.id);
    },
    
    // 处理单个选择
    handleSingleSelect(val, id) {
      if (val) {
        if (!this.multipleSelection.includes(id)) {
          this.multipleSelection.push(id);
        }
      } else {
        this.multipleSelection = this.multipleSelection.filter(item => item !== id);
      }
    },
    
    // 根据接口类型展示不同的样式
    getRowClassName(row) {
      switch (row) {
        case 'GET':
          // return '--el-card-border-color:#61affe;background-color:rgba(97,175,254,.1)'
          return '--el-card-border-color:#61affe'
        case 'POST':
          // return '--el-card-border-color:#49cc90;background-color:rgba(73,204,144,.1)'
          return '--el-card-border-color:#49cc90'
        case 'PUT':
          // return '--el-card-border-color:#fca130;background-color:rgba(252,161,48,.1)'
          return '--el-card-border-color:#49cc90'
        case 'DELETE':
          // return '--el-card-border-color:#f93e3e;background-color:rgba(249,62,62,.1)'
          return '--el-card-border-color:#f93e3e'
        case 'PATCH':
          // return '--el-card-border-color:#50e3c2;background-color:rgba(80,227,194,.1)'
          return '--el-card-border-color:#50e3c2'
        default:
          return '';
    }
  },

    // 根据对应节点展示接口信息
    async handleTreeClick(id,filterText,creator) {
      let project_id = this.pro.id;
      if(filterText) {
      let name = filterText.name;
      let status = filterText.status;
      const response = await this.$api.getNewInterfaces(id,project_id,name,status);
      if (response.status === 200) {
        this.treeId = id;
        this.tableData = response.data;
        this.interfaceCount = response.data.length;
      }} else if(creator){
        let name = filterText.name;
        let status = filterText.status;
        const response = await this.$api.getNewInterfaces(id,project_id,name,status,creator);
        if (response.status === 200) {
          this.treeId = id;
          this.tableData = response.data;
          this.interfaceCount = response.data.length;
        }
      } else {
        const response = await this.$api.getNewInterfaces(id,project_id);
        if (response.status === 200) {
          this.treeId = id;
          this.tableData = response.data;
          this.interfaceCount = response.data.length;
        }
      }
    },

    // 单个接口信息删除接口
    async delInterface(id){
      const response = await this.$api.deleteNewInterface(id);
			if (response.status === 204) {
        ElMessage({
          type: 'success',
          message: '删除成功',
          duration: 1000
        });
      this.handleTreeClick(this.treeId);
      this.filterText={status: '',name:''};
      this.$refs.multipleTable.clearSelection();
      }
    },
    // 批量接口信息删除接口
    async delAllInterface(){
      if (this.multipleSelection.length === 0) {
          ElMessage({
            type: 'warning',
            message: '请勾选数据后再操作！',
            duration: 2000
          });
          return;
        }
      const params = {"item_ids":this.multipleSelection}
      const response = await this.$api.deleteAllNewInterfaces(params);
			if (response.status === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
          duration: 1000
        });
      this.handleTreeClick(this.treeId);
      this.filterText={status: '',name:''};
      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();
      }
    },

    // 点击查询
    handlenewInterfacesClick() {
      this.handleTreeClick(this.treeId,this.filterText)
    },

    // 主节点点击添加
    clickAdd() {
			this.addCaseDlg = true;
		},

    // 点击删除
    clickDel(id) {
			ElMessageBox.confirm('确定要删除该接口吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.delInterface(id);
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '取消删除',
						duration: 1000
					});
				});
		},

    handleClose() {
      this.addCaseDlg = false;
      this.editCaseDlg = false;
      this.mockDlg = false;
      this.copyDlg = false;
      this.handleTreeClick(this.treeId);
    },

    clickEditStep(id) {
      this.Interface_id = id
      this.editCaseDlg = true
      this.$nextTick(() => {
        this.$refs.childRef.getInterfaceInfo(this.Interface_id);
      })
    },

    // 复制用例
		clickCopy(id) {
      this.copyDlg = true;
      this.clickEditStep(id)
    },
    // 操作记录
		clickLog() {
      this.logDlg = true;

    },
    // 只看自己创建的接口
    userInterface() {
      this.showOnlySelf = !this.showOnlySelf;
       if (this.showOnlySelf) {
        // 只看自己创建的逻辑
        this.handleTreeClick(this.treeId,'',this.username);
      } else {
        // 取消只看自己创建的逻辑
        this.handleTreeClick(this.treeId);
      }
    },

    confirmSelection() {
      this.env = this.selectedEnvironment; // 在确认选择时更新 env 数据
      this.selectedEnvironmentName = this.testEnvs.find(env => env.id === this.selectedEnvironment).name;
      this.dialogVisible = false;
    },
    importClick() {
    this.importDlg = true;
    },
    handleCloseModal() {
      this.importDlg = false; // 关闭弹窗
      this.handleTreeClick(this.treeId);
    },
    buttonColor(status) {
    switch (status) {
      case '已发布':
        return '#67C23A';
      case '测试中':
        return '#626aef';
      case '开发中':
        return '#E6A23C';
      case '已废弃':
        return '#909399';
      default:
        return '#409eff';
    }
    },
  async statusClick(status,id){
    let params = {"status":status}
    const response = await this.$api.updateNewInterface(id, params);
        if (response.status === 200) {
          this.handleTreeClick(this.treeId)
        }
    },

  handleChildData(data) {
    this.interfaceData = data
    this.mockDlg = true;
  },
  }
};
</script>

<style scoped>
.interface-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  width: 100%;
  overflow-x: hidden;
}

.main-content {
  margin: 0;
  width: 100%;
}

.left-panel {
  padding: 10px;
  height: 100%;
}

.right-content {
  padding: 10px 15px;
  background-color: #f5f7fa;
}

.search-area {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
}

.env-info {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.interface-title {
  clear: both;
  font-weight: 500;
  margin-top: 10px;
  margin-bottom: 15px;
  border-left: 3px solid #2395f1;
  padding-left: 10px;
  font-size: 15px;
  color: #303133;
}

.interface-scrollbar {
  height: calc(100vh - 250px);
  min-height: 400px;
}

.interface-list {
  width: 100%;
}

.interface-item {
  display: flex;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-left-width: 5px;
}

.method-get {
  border-left-color: #61affe;
}

.method-post {
  border-left-color: #49cc90;
}

.method-put {
  border-left-color: #fca130;
}

.method-delete {
  border-left-color: #f93e3e;
}

.method-patch {
  border-left-color: #50e3c2;
}

.method-dead {
  border-left-color: rgb(201, 233, 104);
}

.interface-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.interface-item-selected {
  border: 1px solid #409eff;
  border-left-width: 5px;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.interface-checkbox {
  display: flex;
  align-items: center;
  padding: 0 15px;
}

.interface-content {
  flex: 1;
  display: flex;
  padding: 18px 0;
  align-items: center;
  cursor: pointer;
  flex-wrap: wrap;
}

.method-section {
  width: 90px;
  display: flex;
  justify-content: center;
  padding: 0 10px;
  margin: 5px 0;
}

.info-section {
  flex: 1;
  padding: 0 15px;
  min-width: 200px;
  overflow: hidden;
  margin: 5px 0;
}

.interface-url {
  font-weight: bold;
  font-size: 15px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 8px;
  color: #303133;
}

.interface-name {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-section {
  width: 120px;
  display: flex;
  justify-content: center;
  padding: 0 10px;
  margin: 5px 0;
}

.status-text {
  font-size: 14px;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.status-text:hover {
  background-color: #f0f2f5;
}

.status-text i {
  margin-right: 5px;
}

.action-section {
  width: 100%;
  max-width: 300px;
  display: flex;
  flex-wrap: wrap;
  padding: 0 15px;
  margin: 5px 0;
}

.action-section .el-button {
  margin: 3px 8px;
  font-size: 13px;
}

.el-tag {
  color: #ffffff;
  width: 70px;
  height: 30px;
  text-align: center;
  font-size: 14px;
  line-height: 30px;
}

.el-dropdown-menu__item i {
  margin-right: 5px;
}

/* Responsive adjustments */
@media screen and (max-width: 768px) {
  .interface-content {
    flex-direction: column;
    align-items: flex-start;
    padding: 10px 0;
  }
  
  .method-section, .info-section, .status-section, .action-section {
    width: 100%;
    justify-content: flex-start;
    padding: 5px 15px;
  }
  
  .info-section {
    order: -1;
  }
  
  .action-section {
    max-width: 100%;
  }
  
  .interface-scrollbar {
    height: calc(100vh - 350px);
  }
  
  .el-tag {
    margin-bottom: 5px;
  }
}
</style>
